<template>
  <div class="medicine-container">
    <el-form :inline="true" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="药品名称:">
            <el-input
              v-model="medicineName"
              placeholder="请输入药品名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="药品分类:">
            <el-select
              v-model="selectedCategoryId"
              placeholder="请选择分类"
              clearable
            >
              <el-option
                v-for="category in categoryList"
                :key="category.medicineCategoryId"
                :label="category.medicineCategoryName"
                :value="category.medicineCategoryId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="处方类型:">
            <el-select
              v-model="prescriptionType"
              placeholder="请选择处方类型"
              clearable
            >
              <el-option label="非处方药" :value=0 />
              <el-option label="处方药" :value=1 />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button
            @click="queryMedicineHandler"
            type="primary"
            class="action-button"
            >查询</el-button
          >
          <el-button
            @click="addMedicineHandler"
            type="primary"
            class="action-button"
            >添加药品</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <el-table :data="tableData" stripe style="width: 100%" class="medicine-table">
      <el-table-column prop="medicineId" label="药品ID" width="80"></el-table-column>
      <el-table-column prop="medicineName" label="药品名称" width="150"></el-table-column>
      <el-table-column prop="medicineCategoryName" label="所属分类" width="120"></el-table-column>
      <el-table-column label="药品封面" width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.medicineCover"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="medicinePrice" label="价格(元)" width="100"></el-table-column>
      <el-table-column prop="medicineNumber" label="库存" width="80"></el-table-column>
      <el-table-column label="处方类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.medicineIsPrescription === 1 ? 'danger' : 'success'">
            {{ scope.row.medicineIsPrescription === 1 ? '处方药' : '非处方药' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用量" width="120">
        <template slot-scope="scope">
          {{ scope.row.medicineDosage || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            @click="detailHandler(scope.row)"
            size="mini"
            class="detail-button"
            >详情</el-button
          >
          <el-button
            @click="updateMedicineHandler(scope.row)"
            size="mini"
            class="update-button"
            >修改</el-button
          >
          <el-button
            @click="deleteHandler(scope.row)"
            size="mini"
            class="delete-button"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container" style="margin-top: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加药品弹窗 -->
    <el-dialog
      title="添加药品"
      :visible.sync="addDialogVisible"
      width="80%"
      class="add-dialog"
    >
      <el-form class="add-form" label-width="120px" :model="addMedicineData">
        <el-row :gutter="20">
          <!-- 左侧列 -->
          <el-col :span="12">
            <el-form-item label="药品名称" prop="medicineName" required>
              <el-input
                v-model="addMedicineData.medicineName"
                placeholder="请输入药品名称"
              ></el-input>
            </el-form-item>

            <el-form-item label="药品分类" prop="medicineCategoryId" required>
              <el-select
                v-model="addMedicineData.medicineCategoryId"
                placeholder="请选择分类"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categoryList"
                  :key="category.medicineCategoryId"
                  :label="category.medicineCategoryName"
                  :value="category.medicineCategoryId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="药品价格" prop="medicinePrice">
              <el-input-number
                v-model="addMedicineData.medicinePrice"
                :min="0"
                :precision="2"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="库存数量" prop="medicineNumber">
              <el-input-number
                v-model="addMedicineData.medicineNumber"
                :min="0"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="是否为处方药" prop="medicineIsPrescription">
              <el-radio-group v-model="addMedicineData.medicineIsPrescription">
                <el-radio :label="0">非处方药</el-radio>
                <el-radio :label="1">处方药</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="药品用量" prop="medicineDosage">
              <el-input
                v-model="addMedicineData.medicineDosage"
                placeholder="请输入药品用量（如：一次2粒，一日3次）"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 右侧列 -->
          <el-col :span="12">
            <el-form-item label="药品封面">
              <image-upload
                @upload-success="handleAddUploadSuccess"
                style="margin-bottom: 20px;"
              ></image-upload>
              <el-image
                v-if="addMedicineData.medicineCover"
                style="width: 120px; height: 120px; border: 1px dashed #ddd; border-radius: 4px;"
                :src="addMedicineData.medicineCover"
                fit="cover"
              ></el-image>
            </el-form-item>

            <el-form-item label="药品描述" prop="medicineDescription">
              <el-input
                type="textarea"
                :rows="3"
                v-model="addMedicineData.medicineDescription"
                placeholder="请输入药品描述"
              ></el-input>
            </el-form-item>

            <el-form-item label="注意事项" prop="medicineNotes">
              <el-input
                type="textarea"
                :rows="3"
                v-model="addMedicineData.medicineNotes"
                placeholder="请输入注意事项"
              ></el-input>
            </el-form-item>

            <el-form-item label="功效" prop="medicineEfficacy">
              <el-input
                type="textarea"
                :rows="3"
                v-model="addMedicineData.medicineEfficacy"
                placeholder="请输入功效"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="addMedicineConfirmHandler"
          class="confirm-button"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改药品弹窗 -->
    <el-dialog
      title="修改药品"
      :visible.sync="updateDialogVisible"
      width="80%"
      class="update-dialog"
    >
      <el-form class="update-form" label-width="120px" :model="updateMedicineData">
        <el-row :gutter="20">
          <!-- 左侧列 -->
          <el-col :span="12">
            <el-form-item label="药品名称" prop="medicineName" required>
              <el-input
                v-model="updateMedicineData.medicineName"
                placeholder="请输入药品名称"
              ></el-input>
            </el-form-item>

            <el-form-item label="药品分类" prop="medicineCategoryId" required>
              <el-select
                v-model="updateMedicineData.medicineCategoryId"
                placeholder="请选择分类"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categoryList"
                  :key="category.medicineCategoryId"
                  :label="category.medicineCategoryName"
                  :value="category.medicineCategoryId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="药品价格" prop="medicinePrice">
              <el-input-number
                v-model="updateMedicineData.medicinePrice"
                :min="0"
                :precision="2"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="库存数量" prop="medicineNumber">
              <el-input-number
                v-model="updateMedicineData.medicineNumber"
                :min="0"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="是否为处方药" prop="medicineIsPrescription">
              <el-radio-group v-model="updateMedicineData.medicineIsPrescription">
                <el-radio :label="0">非处方药</el-radio>
                <el-radio :label="1">处方药</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="药品用量" prop="medicineDosage">
              <el-input
                v-model="updateMedicineData.medicineDosage"
                placeholder="请输入药品用量（如：一次2粒，一日3次）"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 右侧列 -->
          <el-col :span="12">
            <el-form-item label="药品封面">
              <el-image
                style="width: 120px; height: 120px; margin-bottom: 10px; border: 1px dashed #ddd; border-radius: 4px;"
                :src="updateMedicineData.medicineCover"
                fit="cover"
              ></el-image>
              <image-upload
                @upload-success="handleUpdateUploadSuccess"
              ></image-upload>
            </el-form-item>

            <el-form-item label="药品描述" prop="medicineDescription">
              <el-input
                type="textarea"
                :rows="3"
                v-model="updateMedicineData.medicineDescription"
                placeholder="请输入药品描述"
              ></el-input>
            </el-form-item>

            <el-form-item label="注意事项" prop="medicineNotes">
              <el-input
                type="textarea"
                :rows="3"
                v-model="updateMedicineData.medicineNotes"
                placeholder="请输入注意事项"
              ></el-input>
            </el-form-item>

            <el-form-item label="功效" prop="medicineEfficacy">
              <el-input
                type="textarea"
                :rows="3"
                v-model="updateMedicineData.medicineEfficacy"
                placeholder="请输入功效"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="updateMedicineConfirmHandler"
          class="confirm-button"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 药品详情弹窗 -->
    <el-dialog
      title="药品详情"
      :visible.sync="detailDialogVisible"
      width="60%"
      class="detail-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="药品ID">{{ detailData.medicineId }}</el-descriptions-item>
        <el-descriptions-item label="药品名称">{{ detailData.medicineName }}</el-descriptions-item>
        <el-descriptions-item label="所属分类">{{ detailData.medicineCategoryName }}</el-descriptions-item>
        <el-descriptions-item label="处方类型">
          <el-tag :type="detailData.medicineIsPrescription === 1 ? 'danger' : 'success'">
            {{ detailData.medicineIsPrescription === 1 ? '处方药' : '非处方药' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="药品封面">
          <el-image
            style="width: 120px; height: 120px;"
            :src="detailData.medicineCover"
            fit="cover"
          ></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="价格">{{ detailData.medicinePrice }} 元</el-descriptions-item>
        <el-descriptions-item label="库存">{{ detailData.medicineNumber }}</el-descriptions-item>
        <el-descriptions-item label="药品用量">{{ detailData.medicineDosage || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(detailData.medicineCreateTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(detailData.medicineUpdateTime) }}</el-descriptions-item>
        <el-descriptions-item label="药品描述" :span="2">{{ detailData.medicineDescription || '-' }}</el-descriptions-item>
        <el-descriptions-item label="注意事项" :span="2">{{ detailData.medicineNotes || '-' }}</el-descriptions-item>
        <el-descriptions-item label="功效" :span="2">{{ detailData.medicineEfficacy || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" class="cancel-button">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMedicine,
  listMedicine,
  updateMedicine,
  deleteMedicine
} from "@/api/drugs/medicine";
import {
  listMedicineCategory
} from "@/api/drugs/medicineCategory";
import ImageUpload from "@/components/ImageUpload";

export default {
  components: {
    ImageUpload
  },
  data() {
    return {
      medicineName: null,
      selectedCategoryId: null,
      prescriptionType: null, // 处方类型筛选
      addDialogVisible: false,
      updateDialogVisible: false,
      detailDialogVisible: false,
      tableData: [],
      categoryList: [], // 存储药品分类列表
      total: 0,
      currentPage: 1,
      pageSize: 10,

      // 添加药品数据
      addMedicineData: {
        medicineName: null,
        medicineCategoryId: null,
        medicineCover: null,
        medicinePrice: 0,
        medicineNumber: 0,
        medicineIsPrescription: 0,
        medicineDosage: null,
        medicineDescription: null,
        medicineNotes: null,
        medicineEfficacy: null
      },

      // 修改药品数据
      updateMedicineData: {
        medicineId: null,
        medicineName: null,
        medicineCategoryId: null,
        medicineCover: null,
        medicinePrice: 0,
        medicineNumber: 0,
        medicineIsPrescription: 0,
        medicineDosage: null,
        medicineDescription: null,
        medicineNotes: null,
        medicineEfficacy: null
      },

      // 详情数据
      detailData: {}
    };
  },
  methods: {
    // 格式化时间
    formatDate(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
        .getHours()
        .toString()
        .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
    },

    // 查询药品
    queryMedicineHandler() {
      listMedicine({
        medicineName: this.medicineName,
        medicineCategoryId: this.selectedCategoryId,
        medicineIsPrescription: this.prescriptionType,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data;
          this.total = res.total;
        }
      });
    },

    // 加载药品分类列表
    loadCategoryList() {
      listMedicineCategory({}).then(res => {
        if (res.code === 200) {
          this.categoryList = res.data;
        }
      });
    },

    // 添加药品
    addMedicineHandler() {
      this.addDialogVisible = true;
      this.addMedicineData = {
        medicineName: null,
        medicineCategoryId: null,
        medicineCover: null,
        medicinePrice: 0,
        medicineNumber: 0,
        medicineIsPrescription: 0,
        medicineDosage: null,
        medicineDescription: null,
        medicineNotes: null,
        medicineEfficacy: null
      };
    },

    // 添加药品封面上传成功
    handleAddUploadSuccess(data) {
      this.addMedicineData.medicineCover = data.fileUrl;
    },

    // 确认添加
    addMedicineConfirmHandler() {
      addMedicine(this.addMedicineData).then(res => {
        if (res.code === 200) {
          this.$message.success("添加成功");
          this.addDialogVisible = false;
          this.queryMedicineHandler();
        } else {
          this.$message.error("添加失败");
        }
      });
    },

    // 删除药品
    deleteHandler(row) {
      this.$confirm(`确定要删除【${row.medicineName}】吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteMedicine(row.medicineId).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.queryMedicineHandler();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },

    // 修改药品
    updateMedicineHandler(row) {
      this.updateDialogVisible = true;
      // 深拷贝数据，避免直接修改
      this.updateMedicineData = Object.assign({}, row);
    },

    // 修改药品封面上传成功
    handleUpdateUploadSuccess(data) {
      this.updateMedicineData.medicineCover = data.fileUrl;
    },

    // 确认修改
    updateMedicineConfirmHandler() {
      updateMedicine(this.updateMedicineData).then(res => {
        if (res.code === 200) {
          this.$message.success("修改成功");
          this.updateDialogVisible = false;
          this.queryMedicineHandler();
        } else {
          this.$message.error("修改失败");
        }
      });
    },

    // 查看详情
    detailHandler(row) {
      this.detailData = Object.assign({}, row);
      this.detailDialogVisible = true;
    },

    // 分页相关
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.queryMedicineHandler();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.queryMedicineHandler();
    }
  },
  mounted() {
    this.loadCategoryList(); // 加载药品分类
    this.queryMedicineHandler(); // 加载药品列表
  }
};
</script>

<style scoped>
.medicine-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-button {
  margin-left: 10px;
}

.medicine-table {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detail-button {
  background-color: #909399;
  color: white;
}

.update-button {
  background-color: #409eff;
  color: white;
}

.delete-button {
  background-color: #f56c6c;
  color: white;
}

.add-dialog, .update-dialog, .detail-dialog {
  border-radius: 8px;
}

.add-form, .update-form {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.cancel-button {
  margin-right: 15px;
}

.confirm-button {
  min-width: 100px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
